<template>
  <div class="message">
    <el-popover placement="bottom" popper-class="custom-pop" width="350px" trigger="click">
      <template #reference>
        <el-badge :hidden="!unReadMsgCount()" :value="unReadMsgCount()" class="item">
          <i :class="'iconfont icon-xiaoxi'" class="toolBar-icon"></i>
        </el-badge>
      </template>
      <el-tabs v-model="activeName">
        <el-tab-pane :label="`内部(${InternalList.length})`" name="first">
          <div v-if="InternalList.length" class="message-list">
            <div class="message-item" v-for="(item, index) in InternalList.slice(0, 6)" :key="item.MDI_ID" @click="read(item)">
              <div class="item-left">
                <img :src="getImagePath(index)" alt="" class="message-icon" />
                <div class="message-content">
                  <el-tooltip effect="dark" :content="item.MDI_Title" placement="top">
                    <span class="message-title">{{ item.MDI_Title }} 🧡</span>
                  </el-tooltip>
                  <el-tooltip effect="dark" :content="item.MDI_Url" placement="top">
                    <span v-if="item.MDI_Url" class="message-url" @click="toPage(item.MDI_Url)">{{ item.MDI_Url }}</span>
                  </el-tooltip>
                  <ul>
                    <el-button icon="FolderOpened" link type="primary" @click="getData(item)"> 附件： </el-button>
                    <el-tooltip
                      v-for="msg in item.fileList"
                      :key="msg.AI_Index"
                      effect="dark"
                      :content="msg.AI_Name"
                      placement="top"
                    >
                      <li @click="download(msg)">{{ msg.AI_Name }}</li>
                    </el-tooltip>
                  </ul>
                  <span class="message-date">{{ timeDifference(item.MDI_Create_Time) }}</span>
                </div>
              </div>
              <div class="item-right" :style="`color: ${hasReadMsgIds.includes(item.MDI_ID) ? '#67c23a' : '#f56c6c'}`">
                {{ hasReadMsgIds.includes(item.MDI_ID) ? "已读" : "未读" }}
              </div>
            </div>
          </div>
          <div v-else class="message-empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无消息</div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`行业(${IndustryList.length})`" name="second">
          <div v-if="IndustryList.length" class="message-list">
            <div class="message-item" v-for="(item, index) in IndustryList.slice(0, 6)" :key="item.MDI_ID" @click="read(item)">
              <div class="item-left">
                <img :src="getImagePath(index + 5)" alt="" class="message-icon" />
                <div class="message-content">
                  <el-tooltip effect="dark" :content="item.MDI_Title" placement="top">
                    <span class="message-title">{{ item.MDI_Title }} 🧡</span>
                  </el-tooltip>
                  <el-tooltip effect="dark" :content="item.MDI_Url" placement="top">
                    <span v-if="item.MDI_Url" class="message-url" @click="toPage(item.MDI_Url)">{{ item.MDI_Url }}</span>
                  </el-tooltip>
                  <ul>
                    <el-button icon="FolderOpened" link type="primary" @click="getData(item)"> 附件： </el-button>
                    <el-tooltip
                      v-for="msg in item.fileList"
                      :key="msg.AI_Index"
                      effect="dark"
                      :content="msg.AI_Name"
                      placement="top"
                    >
                      <li @click="download(msg)">{{ msg.AI_Name }}</li>
                    </el-tooltip>
                  </ul>
                  <span class="message-date">{{ timeDifference(item.MDI_Create_Time) }}</span>
                </div>
              </div>
              <div class="item-right" :style="`color: ${hasReadMsgIds.includes(item.MDI_ID) ? '#67c23a' : '#f56c6c'}`">
                {{ hasReadMsgIds.includes(item.MDI_ID) ? "已读" : "未读" }}
              </div>
            </div>
          </div>
          <div v-else class="message-empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无消息</div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`政策(${PolicyList.length})`" name="third">
          <div v-if="PolicyList.length" class="message-list">
            <div class="message-item" v-for="(item, index) in PolicyList.slice(0, 6)" :key="item.MDI_ID" @click="read(item)">
              <div class="item-left">
                <img :src="getImagePath(index)" alt="" class="message-icon" />
                <div class="message-content">
                  <el-tooltip effect="dark" :content="item.MDI_Title" placement="top">
                    <span class="message-title">{{ item.MDI_Title }} 🧡</span>
                  </el-tooltip>
                  <el-tooltip effect="dark" :content="item.MDI_Url" placement="top">
                    <span v-if="item.MDI_Url" class="message-url" @click="toPage(item.MDI_Url)">{{ item.MDI_Url }}</span>
                  </el-tooltip>
                  <ul>
                    <el-button icon="FolderOpened" link type="primary" @click="getData(item)"> 附件： </el-button>
                    <el-tooltip
                      v-for="msg in item.fileList"
                      :key="msg.AI_Index"
                      effect="dark"
                      :content="msg.AI_Name"
                      placement="top"
                    >
                      <li @click="download(msg)">{{ msg.AI_Name }}</li>
                    </el-tooltip>
                  </ul>
                  <span class="message-date">{{ timeDifference(item.MDI_Create_Time) }}</span>
                </div>
              </div>
              <div class="item-right" :style="`color: ${hasReadMsgIds.includes(item.MDI_ID) ? '#67c23a' : '#f56c6c'}`">
                {{ hasReadMsgIds.includes(item.MDI_ID) ? "已读" : "未读" }}
              </div>
            </div>
          </div>
          <div v-else class="message-empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无代办</div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { saveAs } from "file-saver";
import { useRouter } from "vue-router";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { timeDifference } from "@/utils/formatter";

const { proxy } = useCurrentInstance();
const router = useRouter();
const activeName = ref("first");

const InternalList = ref<any>([]); // 内部
const IndustryList = ref<any>([]); // 行业
const PolicyList = ref<any>([]); // 政策

// 所有消息存储
const allMessages = ref<any>([]);
// 已读消息存储
const hasReadMsgIds = ref<any>([]);

// 动态添加图片
const getImagePath = (index: number) => {
  return new URL(`../../../../assets/images/msg0${index + 1}.png`, import.meta.url).href;
};

const toPage = (url: string) => {
  if (url.includes("http")) {
    window.open(url);
    return;
  }
  router.push(url);
};

// 获取消息所对应的附件
const getData = (data: any) => {
  proxy.$vueAxios
    .post("Master_Base_AllInfos/GetConditional", {
      order: "AI_Index asc",
      dtoList: [{ fieldName: "Record_ID", fieldValue: data.MDI_ID }]
    })
    .then((res: any) => {
      console.log("res---------", res);
      data.fileList = res.List;
    });
};

// 下载
const download = async (item: any) => {
  console.log("item----", item);
  if (item) {
    console.log("jinru");
    const btey = 1024 * 1024 * 10; // 分片大小为10m
    const totalPieces = Math.ceil(item.AI_Source_Size / btey);
    let arr: any[] = [];
    for (let i = 0; i < totalPieces; i++) {
      const data = await proxy.$vueAxios.download2(
        "MasterBaseAllInfos/Download",
        {
          AI_ID: item.AI_ID,
          pieceTotal: totalPieces,
          piece: i + 1
        },
        { noLoading: true }
      );
      const percent = Math.ceil(((i + 1) / totalPieces) * 100);
      proxy.$showLoading({ tip: `文件下载请求中...(${percent}%)` });
      arr = [...arr, data];
    }
    const fileBlob = new Blob(arr, { type: "application/octet-stream;charset=utf-8" });
    saveAs(fileBlob, item.AI_Name);
    proxy.$hideLoading();
  } else {
    proxy.$message.warning("请选择要下载的文件!");
  }
};

// 获取消息
const getMsgs = () => {
  const readedMsg = localStorage.getItem("readed_Msg");
  hasReadMsgIds.value = readedMsg ? JSON.parse(readedMsg) : [];
  proxy.$vueAxios
    .get("/Master_Base_MsgDocInfo/Get", {
      order: "MDI_Order asc",
      pageIndex: 1,
      pageSize: 15
    })
    .then((res: any) => {
      res.List.forEach((msg: any) => {
        if (msg.MDI_Type === "内部" && msg.MDI_Enable) {
          InternalList.value.push(msg);
        }
        if (msg.MDI_Type === "行业" && msg.MDI_Enable) {
          IndustryList.value.push(msg);
        }
        if (msg.MDI_Type === "政策" && msg.MDI_Enable) {
          PolicyList.value.push(msg);
        }
      });
      allMessages.value.push(...InternalList.value, ...IndustryList.value, ...PolicyList.value);
      console.log("InternalList.value1", InternalList.value);
      console.log("IndustryList.value2", IndustryList.value);
      console.log("PolicyList.value2", PolicyList.value);
      console.log("allMessages-------", allMessages.value);
    });
};

// 已读消息
const read = (msg: any) => {
  if (!hasReadMsgIds.value.includes(msg.MDI_ID)) {
    hasReadMsgIds.value.push(msg.MDI_ID);
    localStorage.setItem("readed_Msg", JSON.stringify(hasReadMsgIds.value));
  }
};

// 未读消息总数
const unReadMsgCount = () => {
  const unReadList = allMessages.value.filter((msg: any) => !hasReadMsgIds.value.includes(msg.MDI_ID));
  return unReadList.length;
};

onMounted(() => {
  getMsgs();
});
</script>

<style>
.custom-pop {
  max-height: 65vh;
  overflow-y: scroll;
}
</style>

<style scoped lang="scss">
@mixin text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.message-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 260px;
  line-height: 45px;
}
.message-list {
  display: flex;
  flex-direction: column;
  .message-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 0;
    cursor: pointer;
    border-bottom: 1px solid var(--el-border-color-light);
    .item-left {
      display: flex;
      align-items: center;
      img {
        align-self: flex-start;
        border-radius: 50%;
      }
    }
    .item-right {
      word-break: keep-all;
    }
    &:last-child {
      border: none;
    }
    .message-icon {
      width: 40px;
      height: 40px;
      margin: 0 20px 0 5px;
    }
    .message-content {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      width: 202px;
      .message-title {
        max-width: 100%;
        margin-bottom: 5px;
        @include text-ellipsis;
      }
      .message-url {
        max-width: 100%;
        margin-bottom: 4px;
        color: #007bff;
        @include text-ellipsis;
        &:hover {
          color: #0056b3;
          text-decoration: underline;
        }
      }
      ul {
        padding: 0;
        margin: 0;
        margin-bottom: 4px;
        li {
          width: 100%;
          padding-left: 20px;
          font-size: 13px;
          line-height: 20px;
          color: #007bff;
          word-break: keep-all;
          list-style: none;
          @include text-ellipsis;
          &:hover {
            color: #0056b3;
            text-decoration: underline;
          }
        }
      }
      .message-date {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }
}
</style>
